package com.yyx.server.controller;

import com.yyx.server.pojo.Admin;
import com.yyx.server.service.AdminService;
import com.yyx.server.vo.LoginVo;
import com.yyx.server.vo.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 登录
 * @author YongXin
 * @date Created in 2021/7/24 23:49
 */
@RestController
@Api(tags = "用户登录")
public class LoginController {

    @Autowired
    private AdminService adminService;
    @ApiOperation(value = "登录返回token")
    @PostMapping("/login")
    public ResultVo login(@RequestBody LoginVo loginVo,HttpServletRequest request){
        return adminService.login(loginVo.getUsername(),loginVo.getPassword(),loginVo.getCode(),request);
    }

    @ApiOperation("获取当前登录用户信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal){
        if (principal==null){
            return null;
        }
        String name = principal.getName();
        Admin admin = adminService.getAdminByUserName(name);
        admin.setPassword(null);
        admin.setRoles(adminService.getRoles(admin.getId()));
        return admin;
    }


    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public ResultVo logout(){
        return ResultVo.success("注销成功");
    }
}
